package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Autowired
    private SpuInfoDescService spuInfoDescService;


    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;


    @Autowired
    private SkuImagesService skuImagesService;
@Autowired
private SkuInfoService skuInfoService;

@Autowired
private CouponFeignService couponFeignService;

@Autowired
private SkuSaleAttrValueService skuSaleAttrValueService;


    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vos) {
        // 1. 保存spu基本信息  pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vos,spuInfoEntity);
        spuInfoEntity.setUpdateTime(new Date());
        spuInfoEntity.setCreateTime(new Date());

        this.save(spuInfoEntity);

        // 2. 保存spu的描述图片   pms_spu_info_desc
        List<String> decript = vos.getDecript();

        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());

        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        //3. 保存spu的图片集 pms_spu_image
        List<String> images = vos.getImages();

        spuImagesService.saveImages(spuInfoEntity.getId(),images);

        // 4. 保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = vos.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(item.getAttrId());

            AttrEntity byId = attrService.getById(item.getAttrId());

            productAttrValueEntity.setAttrName(byId.getAttrName());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());

            return productAttrValueEntity;
        }).collect(Collectors.toList());

        productAttrValueService.saveProductAttr(collect);


        //5 保存spu的积分信息，  gulimall_sms->sms_spu_bounds
        Bounds bounds = vos.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R spuBoundsRes = couponFeignService.saveSpuBounds(spuBoundTo);
        if (spuBoundsRes.getCode()!=0){
            log.error("远程保存积分信息失败");
        }

        //5.1 sku的基本信息
        List<Skus> skus = vos.getSkus();
        if(skus!=null&&skus.size()!=0){
            skus.forEach(item->{
           String defaultImg ="";
                for(Images image:item.getImages()){
                    if(image.getDefaultImg()==1){
                        defaultImg =image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());

                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());

                    return skuImagesEntity;

                }).filter(enity->{
                    return StringUtils.isNotEmpty(enity.getImgUrl());
                }).collect(Collectors.toList());

                //5.2 保存sku的图片信息
                skuImagesService.saveBatch(skuImagesEntities);

                //5.3  sku的销售属性
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(attr1 -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();

                    BeanUtils.copyProperties(attr1, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setAttrId(attr1.getAttrId());
                    skuSaleAttrValueEntity.setSkuId(skuId);

                    return skuSaleAttrValueEntity;

                }).collect(Collectors.toList());

                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // 5.4 sku的优惠，满减等
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
//                skuReductionTo.setMemberPrice(item.getMemberPrice());
                if (skuReductionTo.getFullCount()>0||skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO)==1){
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    if(r.getCode()!=0){
                        log.error("远程保存spu满减信息失败");
                    }
                }

            });



        }



    }

//spu的查询总数据 检索等
    @Override
    public PageUtils queryPageByConditions(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            wrapper.and(item->{
                item.eq("id",key).or().like("spu_name",key);
            });
        }

        String status = (String) params.get("status");

        if(StringUtils.isNotEmpty(status)){
            wrapper.eq("publish_status",status);
        }

        String brandId = (String) params.get("brandId");

        if(StringUtils.isNotEmpty(brandId) &&!"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if(StringUtils.isNotEmpty(catelogId) &&!"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;
    
    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    //商品上架
    @Override
    public void up(Long spuId) {
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);

        //4. 查询所有可以的规格属性  根据spuId 查询
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrlistforspu(spuId);

        List<Long> attrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);

        HashSet<Long> idSet = new HashSet<>(searchAttrIds);


        //检索属性
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(attr -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            attrs.setAttrId(attr.getId());
            attrs.setAttrName(attr.getAttrName());
            attrs.setAttrValue(attr.getAttrValue());

            return attrs;
        }).collect(Collectors.toList());
        System.out.println(attrsList);
        
        //统一查到 每个sku 是否有库存
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());


        Map<Long, Boolean> stockMap = null;
        try{
            R skusHasStock = wareFeignService.getSkusHasStock(skuIds);

            List<SkuHasStockVo> data= (List<SkuHasStockVo>) skusHasStock.get("data");
           stockMap = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo->SkuHasStockVo.getHasStock()));
        }catch (Exception e){
            log.error("库存服务远程查询异常{}",e);
        }


        System.out.println(stockMap);

        //开始封装数据
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProduct = skus.stream().map(sku -> {
            //需要组装这样的数据
            SkuEsModel skuEsModel = new SkuEsModel();

            BeanUtils.copyProperties(sku,skuEsModel);

            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());

            //1.发送远程调用  库存系统查询是否有库存
          if (finalStockMap ==null){
              skuEsModel.setHasStock(true);
          }else{
              skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId()));
          }

            //2. 热度评分

            skuEsModel.setHotScore(0L);


            //3. 查询品牌和分类信息
            BrandEntity brand = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brand.getName());
            skuEsModel.setBrandImg(brand.getLogo());

            CategoryEntity category = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(category.getName());

            //设置检索属性
            skuEsModel.setAttrs(attrsList);

            return skuEsModel;
        }).collect(Collectors.toList());

        //5. 将数据发送es进行保存
        R r = searchFeignService.productStatusUp(upProduct);
        if (r.getCode() == 0){
            baseMapper.updateSpuStatus(spuId, WareConstant.StatusEnum.SPU_UP.getCode());
        }else{
            //远程调用失败
            //TODO 重复调用机制

        }

    }

    @Override
    public SpuInfoEntity getSpuBySkuId(Long skuId) {

        SkuInfoEntity byId = skuInfoService.getById(skuId);

        SpuInfoEntity entity = getById(byId.getSpuId());

        return entity;
    }

}